package com.qiaoba.module.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.qiaoba.common.base.constant.BaseConstant;
import com.qiaoba.common.base.exception.ServiceException;
import com.qiaoba.module.system.converter.SysDeptConverter;
import com.qiaoba.module.system.entity.SysDept;
import com.qiaoba.module.system.entity.dto.SysDeptDTO;
import com.qiaoba.module.system.entity.param.SysDeptParam;
import com.qiaoba.module.system.mapper.SysDeptMapper;
import com.qiaoba.module.system.service.SysDeptService;
import jodd.bean.BeanUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 部门 服务层实现
 *
 * @author ailanyin
 * @date 2023-09-10 22:08:18
 */
@Service
@RequiredArgsConstructor
public class SysDeptServiceImpl implements SysDeptService {

    private final SysDeptMapper sysDeptMapper;

    @Override
    public int insert(SysDeptDTO dto) {
        handleParentId(dto);
        checkDeptNameUnique(dto.getDeptId(), dto.getParentId(), dto.getDeptName());
        SysDept sysDept = SysDeptConverter.dto2Entity(dto);
        if (BaseConstant.DEFAULT_PARENT_ID_VALUE.equals(sysDept.getParentId())) {
            return sysDeptMapper.insert(sysDept);
        }
        SysDept info = sysDeptMapper.selectById(sysDept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (BaseConstant.ABNORMAL.equals(info.getStatus())) {
            throw new ServiceException("上级部门停用，不允许新增");
        }
        // 设置祖级
        sysDept.setAncestors(info.getAncestors() + BaseConstant.DEFAULT_SPLIT_STR + sysDept.getParentId());
        return sysDeptMapper.insert(sysDept);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(SysDeptDTO dto) {
        handleParentId(dto);
        checkDeptNameUnique(dto.getDeptId(), dto.getParentId(), dto.getDeptName());
        SysDept sysDept = SysDeptConverter.dto2Entity(dto);
        SysDept newParentDept = sysDeptMapper.selectById(sysDept.getParentId());
        // 如果新的父节点为非正常状态,则不允许新增子节点
        if (Objects.nonNull(newParentDept) && BaseConstant.ABNORMAL.equals(newParentDept.getStatus())) {
            throw new ServiceException("上级部门停用，不允许插入");
        }
        SysDept oldDept = sysDeptMapper.selectById(sysDept.getDeptId());
        if (Objects.nonNull(newParentDept) && Objects.nonNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + BaseConstant.DEFAULT_SPLIT_STR + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            sysDept.setAncestors(newAncestors);
            updateDeptChildren(sysDept.getDeptId(), newAncestors, oldAncestors);
        }
        return sysDeptMapper.updateById(sysDept);
    }

    @Override
    public int deleteById(String deptId) {
        if (StrUtil.isNotBlank(sysDeptMapper.existChild(deptId))) {
            throw new ServiceException("存在子级部门，不允许删除");
        }
        String nickname = sysDeptMapper.existUsed(deptId);
        if (StrUtil.isNotBlank(nickname)) {
            throw new ServiceException(StrUtil.format("用户【{}】已绑定该部门，请解绑后删除", nickname));
        }
        return sysDeptMapper.deleteById(deptId);
    }

    @Override
    public SysDept selectById(String deptId) {
        return sysDeptMapper.selectById(deptId);
    }

    @Override
    public List<SysDept> selectList(SysDeptParam param) {
        return sysDeptMapper.selectList(SysDeptConverter.param2Wrapper(param));
    }

    @Override
    public List<SysDept> excludeChild(String deptId) {
        List<SysDept> deptList = selectList(new SysDeptParam());
        deptList.removeIf(dept -> dept.getDeptId().equals(deptId)
                || StrUtil.split(dept.getAncestors(), BaseConstant.DEFAULT_SPLIT_STR).contains(deptId));
        return deptList;
    }

    @Override
    public List<Tree<String>> buildDeptTree(List<SysDept> list) {
        if (CollUtil.isEmpty(list)) {
            return CollUtil.newArrayList();
        }
        TreeNodeConfig config = TreeNodeConfig.DEFAULT_CONFIG.setNameKey(BaseConstant.TREE_KEY_NAME);
        return TreeUtil.build(list, BaseConstant.DEFAULT_PARENT_ID_VALUE, config, (dept, tree) ->
                tree.setId(dept.getDeptId())
                        .setParentId(dept.getParentId())
                        .setName(dept.getDeptName())
                        .setWeight(dept.getOrderNum()));
    }

    @Override
    public List<String> selectDeptIdsByRoleId(String roleId) {
        return sysDeptMapper.selectDeptIdsByRoleId(roleId);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    private void updateDeptChildren(String deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = selectChildrenDeptById(deptId);
        if (CollUtil.isEmpty(children)) {
            return;
        }
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        List<SysDept> list = new ArrayList<>();
        for (SysDept child : children) {
            SysDept dept = new SysDept();
            dept.setDeptId(child.getDeptId());
            dept.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
            list.add(dept);
        }
        if (CollUtil.isEmpty(list)) {
            return;
        }
        Db.updateBatchById(list);
    }

    private List<SysDept> selectChildrenDeptById(String deptId) {
        List<SysDept> deptList = selectList(new SysDeptParam());
        deptList.removeIf(dept -> !StrUtil.split(dept.getAncestors(), BaseConstant.DEFAULT_SPLIT_STR).contains(deptId));
        return deptList;
    }

    private void handleParentId(SysDeptDTO dto) {
        if (StrUtil.isBlank(dto.getParentId())) {
            // 父部门ID为空 -> 说明是一级部门,手动将父部门ID设置成0
            dto.setParentId(BaseConstant.DEFAULT_PARENT_ID_VALUE);
        }
    }

    private void checkDeptNameUnique(String deptId, String parentId, String deptName) {
        if (StrUtil.isNotBlank(sysDeptMapper.checkDeptNameUnique(deptId, parentId, deptName))) {
            throw new ServiceException(StrUtil.format("同级部门下名称不允许重复"));
        }
    }
}
